<!doctype html><html lang=zh-hans>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta http-equiv=x-ua-compatible content="IE=edge">
<meta name=author content="小李刀刀">
<meta name=description content="Spiral 提供了简单易用的文件系统操作组件。该组件在所有的项目类型中均可使用。 Directory Registry 目录注册表 绝大多数的 Spiral 组件都依赖于目录注册表，而不是硬编码路径。目录注册表可以通过 Spiral\Boot\DirectoriesInterface 提供的方法来使用。 配置目录注册表的操作是在应用入口文件（app.php）中进行： $app = \App\App::init([ 'root' => __DIR__, 'customDir' => __DIR__ . '/custom' ]); 或者在引导程序中也">
<meta name=theme-color content="#3f51b5">
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-light>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-dark disabled>
<script src=https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin=anonymous async></script>
<link rel=stylesheet href="https://fonts.font.im/css?family=Source+Code+Pro:300,400,500,600,700&subset=latin-ext&display=swap">
<link rel=stylesheet href=/css/academic.css>
<script>(function(b,d,e,a,g){b[a]=b[a]||[],b[a].push({'gtm.start':(new Date).getTime(),event:'gtm.js'});var f=d.getElementsByTagName(e)[0],c=d.createElement(e),h=a!='dataLayer'?'&l='+a:'';c.async=!0,c.src='https://www.googletagmanager.com/gtm.js?id='+g+h,f.parentNode.insertBefore(c,f)})(window,document,'script','dataLayer','GTM-5KZH8N7')</script>
<link rel=manifest href=/index.webmanifest>
<link rel=icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_3.png>
<link rel=apple-touch-icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_192x192_fill_lanczos_center_3.png>
<link rel=canonical href=https://studyspiral.cn/docs/component/files/>
<meta property="twitter:card" content="summary">
<meta property="og:site_name" content="Spiral中文网">
<meta property="og:url" content="https://studyspiral.cn/docs/component/files/">
<meta property="og:title" content="文件和目录 | Spiral中文网">
<meta property="og:description" content="Spiral 提供了简单易用的文件系统操作组件。该组件在所有的项目类型中均可使用。 Directory Registry 目录注册表 绝大多数的 Spiral 组件都依赖于目录注册表，而不是硬编码路径。目录注册表可以通过 Spiral\Boot\DirectoriesInterface 提供的方法来使用。 配置目录注册表的操作是在应用入口文件（app.php）中进行： $app = \App\App::init([ 'root' => __DIR__, 'customDir' => __DIR__ . '/custom' ]); 或者在引导程序中也"><meta property="og:image" content="https://studyspiral.cn/images/logo.svg">
<meta property="twitter:image" content="https://studyspiral.cn/images/logo.svg"><meta property="og:locale" content="zh-Hans">
<meta property="article:published_time" content="2020-03-16T22:03:24+08:00">
<meta property="article:modified_time" content="2020-04-13T00:00:42+08:00">
<script src=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js integrity="sha256-5VhCqFam2Cn+yjw61zbBNrbHVJ6SRydPeKopYlngbiQ=" crossorigin=anonymous></script>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css integrity="sha256-zQ0LblD/Af8vOppw18+2anxsuaz3pWYyVWi+bTvTH8Q=" crossorigin=anonymous>
<script>window.addEventListener("load",function(){window.cookieconsent.initialise({palette:{popup:{background:"#3f51b5",text:"#fff"},button:{background:"#fff",text:"#3f51b5"}},theme:"classic",content:{message:"本网站使用cookies来确保您在本网站上获得最佳体验。",dismiss:"知道了!",link:"了解更多",href:"https://www.cookiesandyou.com"}})})</script>
<title>文件和目录 | Spiral中文网</title>
</head>
<body id=top data-spy=scroll data-offset=70 data-target=#TableOfContents>
<aside class=search-results id=search>
<div class=container>
<section class=search-header>
<div class="row no-gutters justify-content-between mb-3">
<div class=col-6>
<h1>搜索</h1>
</div>
<div class="col-6 col-search-close">
<a class=js-search href=#><i class="fas fa-times-circle text-muted" aria-hidden=true></i></a>
</div>
</div>
<div id=search-box>
<input name=q id=search-query placeholder=搜索... autocapitalize=off autocomplete=off autocorrect=off spellcheck=false type=search>
</div>
</section>
<section class=section-search-results>
<div id=search-hits>
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id=navbar-main>
<div class=container>
<div class="d-none d-lg-inline-flex">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<button type=button class=navbar-toggler data-toggle=collapse data-target=#navbar-content aria-controls=navbar aria-expanded=false aria-label=切换导航>
<span><i class="fas fa-bars"></i></span>
</button>
<div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<div class="navbar-collapse main-menu-item collapse justify-content-end" id=navbar-content>
<ul class="navbar-nav d-md-inline-flex">
<li class=nav-item>
<a class=nav-link href=/docs/basics/quick-start/><span>教程</span></a>
</li>
<li class=nav-item>
<a class="nav-link active" href=/docs/><span>文档</span></a>
</li>
<li class=nav-item>
<a class=nav-link href=/post/><span>文章</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class=nav-item>
<a class="nav-link js-search" href=#><i class="fas fa-search" aria-hidden=true></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid docs">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 docs-sidebar">
<form class="docs-search d-flex align-items-center">
<button class="btn docs-toggle d-md-none p-0 mr-3" type=button data-toggle=collapse data-target=#docs-nav aria-controls=docs-nav aria-expanded=false aria-label="Toggle section navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<input name=q type=search class=form-control placeholder=搜索... autocomplete=off>
</form>
<nav class="collapse docs-links" id=docs-nav>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/extension/dotenv/>Dotenv</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/>总览</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/>Spiral介绍</a>
</li>
<li>
<a href=/docs/about/contributing/>贡献指引</a>
</li>
<li>
<a href=/docs/about/semver/>版本说明</a>
</li>
<li>
<a href=/docs/about/license/>授权协议</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/psr-15/>定制 PSR-15 处理器</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/start/install/>快速开始</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/start/install/>安装指引</a>
</li>
<li>
<a href=/docs/start/workers/>应用工作进程</a>
</li>
<li>
<a href=/docs/start/structure/>应用程序结构</a>
</li>
<li>
<a href=/docs/start/configuration/>默认配置</a>
</li>
<li>
<a href=/docs/start/commands/>控制台命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/basics/quick-start/>入门基础</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/basics/quick-start/>上手指南</a>
</li>
<li>
<a href=/docs/basics/scaffolding/>脚手架</a>
</li>
<li>
<a href=/docs/basics/prototype/>原型开发辅助</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/framework/design/>核心框架</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/framework/design/>设计理念</a>
</li>
<li>
<a href=/docs/framework/application-server/>应用服务器</a>
</li>
<li>
<a href=/docs/framework/config/>配置对象</a>
</li>
<li>
<a href=/docs/framework/kernel/>内核与环境</a>
</li>
<li>
<a href=/docs/framework/container/>容器</a>
</li>
<li>
<a href=/docs/framework/bootloaders/>引导程序</a>
</li>
<li>
<a href=/docs/framework/scopes/>IoC 作用域</a>
</li>
<li>
<a href=/docs/framework/memory/>静态高速缓存</a>
</li>
<li>
<a href=/docs/framework/finalizers/>终结器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cookbook/annotated-routes/>速查手册</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cookbook/annotated-routes/>注解式路由</a>
</li>
<li>
<a href=/docs/cookbook/injector/>容器注入器</a>
</li>
<li>
<a href=/docs/cookbook/domain-core/>领域内核、控制器</a>
</li>
<li>
<a href=/docs/cookbook/golang-library/>Golang服务集成</a>
</li>
<li>
<a href=/docs/cookbook/custom-dispatcher/>自定义调度器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/component/files/>常用组件</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li class=active>
<a href=/docs/component/files/>文件和目录</a>
</li>
<li>
<a href=/docs/component/reactor/>代码生成</a>
</li>
<li>
<a href=/docs/component/tokenizer/>静态分析工具</a>
</li>
<li>
<a href=/docs/component/metrics/>应用指标</a>
</li>
<li>
<a href=/docs/component/data-grid/>数据网格</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/console/configuration/>控制台</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/console/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/console/commands/>用户命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/configuration/>HTTP</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/http/configuration/>安装配置</a>
</li>
<li>
<a href=/docs/http/lifecycle/>请求生命周期</a>
</li>
<li>
<a href=/docs/http/request-response/>请求和响应</a>
</li>
<li>
<a href=/docs/http/routing/>路由</a>
</li>
<li>
<a href=/docs/http/errors/>错误页面</a>
</li>
<li>
<a href=/docs/http/middleware/>中间件</a>
</li>
<li>
<a href=/docs/http/golang/>Golang 中间件</a>
</li>
<li>
<a href=/docs/http/cookies/>Cookies</a>
</li>
<li>
<a href=/docs/http/session/>Session</a>
</li>
<li>
<a href=/docs/http/csrf/>CSRF 防护</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/security/encrypter/>安全</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/security/encrypter/>数据加密</a>
</li>
<li>
<a href=/docs/security/validation/>数据验证</a>
</li>
<li>
<a href=/docs/security/rbac/>基于角色的权限控制</a>
</li>
<li>
<a href=/docs/security/authentication/>用户认证</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/filters/configuration/>请求过滤</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/filters/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/filters/filter/>过滤器</a>
</li>
<li>
<a href=/docs/filters/composite/>复合过滤器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/database/configuration/>数据库</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/database/configuration/>安装与配置</a>
</li>
<li>
<a href=/docs/database/access/>访问数据</a>
</li>
<li>
<a href=/docs/database/isolation/>逻辑隔离</a>
</li>
<li>
<a href=/docs/database/query-builders/>查询构造器</a>
</li>
<li>
<a href=/docs/database/transactions/>Transactions</a>
</li>
<li>
<a href=/docs/database/introspection/>Schema Introspection</a>
</li>
<li>
<a href=/docs/database/declaration/>Declaration</a>
</li>
<li>
<a href=/docs/database/migrations/>Migrations</a>
</li>
<li>
<a href=/docs/database/errata/>Errata</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cycle/configuration/>Cycle ORM</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cycle/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/queue/configuration/>队列任务</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/queue/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/queue/scraper/>网站爬虫</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/views/configuration/>视图</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/views/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/stempler/configuration/>Stempler 模板</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/stempler/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/stempler/directives/>Directives</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>国际化</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>GRPC</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>事件广播</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>调试及性能</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>扩展</a>
</div>
</nav>
</div>
<div class="d-none d-xl-block col-xl-2 docs-toc">
<ul class="nav toc-top">
<li><a href=# id=back_to_top class=docs-toc-title>在本页</a></li>
</ul>
<nav id=TableOfContents>
<ul>
<li><a href=#directory-registry>Directory Registry</a></li>
<li><a href=#目录注册表>目录注册表</a></li>
<li><a href=#文件>文件</a>
<ul>
<li><a href=#创建文件夹>创建文件夹</a></li>
<li><a href=#删除目录>删除目录</a></li>
</ul>
</li>
<li><a href=#文件信息>文件信息</a>
<ul>
<li><a href=#权限>权限</a></li>
</ul>
</li>
<li><a href=#移动和复制>移动和复制</a>
<ul>
<li><a href=#临时文件>临时文件：</a></li>
</ul>
</li>
<li><a href=#读写操作>读写操作</a>
<ul>
<li><a href=#创建写入文件>创建/写入文件</a></li>
<li><a href=#增加内容>增加内容</a></li>
<li><a href=#touch>Touch</a></li>
<li><a href=#读取文件>读取文件</a></li>
</ul>
</li>
</ul>
</nav>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 docs-content" role=main>
<article class=article>
<div class="alert alert-warning" role=alert>
官方文档中文版翻译工作仍在进行中，欢迎 <a href=/post/join-translation/>参与翻译</a>。
</div>
<div class=docs-article-container>
<h1>文件和目录</h1>
<div class=article-style>
<p>Spiral 提供了简单易用的文件系统操作组件。该组件在所有的项目类型中均可使用。</p>
<h2 id=directory-registry>Directory Registry</h2>
<h2 id=目录注册表>目录注册表</h2>
<p>绝大多数的 Spiral 组件都依赖于目录注册表，而不是硬编码路径。目录注册表可以通过 <code>Spiral\Boot\DirectoriesInterface</code> 提供的方法来使用。</p>
<p>配置目录注册表的操作是在应用入口文件（app.php）中进行：</p>
<pre><code class=language-php>$app = \App\App::init([
    'root'      =&gt; __DIR__,
    'customDir' =&gt; __DIR__ . '/custom'
]);
</code></pre>
<p>或者在引导程序中也可以进行目录注册表的配置：</p>
<pre><code class=language-php>namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Boot\DirectoriesInterface;

class AppBootloader extends Bootloader
{
    public function boot(DirectoriesInterface $directories)
    {
        $directories-&gt;set(
            'customDir',
            $directories-&gt;get('root') . '/custom'
        );
    }
}
</code></pre>
<p>在需要访问注册表中的某个目录的路径时，可以依赖注入 <code>DirectoriesInterface</code> 接口：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Boot\DirectoriesInterface;

class HomeController
{
    public function index(DirectoriesInterface $dirs)
    {
        dump($dirs-&gt;get('root'));
        dump($dirs-&gt;get('customDir'));

        dump($dirs-&gt;getAll());
    }
}
</code></pre>
<blockquote>
<p>在配置文件中，也可以使用 Spiral 提供的全局 <code>directory</code> 函数。但是要注意，这个函数只在 Spiral 框架范围内可用，因为它依赖全局容器的作用域。</p>
</blockquote>
<h2 id=文件>文件</h2>
<p>使用 <code>Spiral\Files\FilesInterface</code> 组件可以对文件系统进行操作：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Files\FilesInterface;

class HomeController
{
    public function index(FilesInterface $files)
    {
        // 递归获取根目录下的所有文件
        dump($files-&gt;getFiles(directory('root')));
    }
}
</code></pre>
<p>在可以使用 <code>PrototypeTraits</code> 的地方，还可以通过它提供的 <code>files</code> 属性来访问文件对象实例：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Prototype\Traits\PrototypeTrait;

class HomeController
{
    use PrototypeTrait;

    public function index()
    {
        dump($this-&gt;files-&gt;exists(__FILE__)); // true
    }
}
</code></pre>
<h3 id=创建文件夹>创建文件夹</h3>
<p>要确保目标文件夹存在（不存在时自动创建），可以通过 <code>ensureDirectory</code> 方法，该方法的第二个参数可以用来指定访问权限：</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Boot\DirectoriesInterface;
use Spiral\Files\FilesInterface;
use Spiral\Prototype\Traits\PrototypeTrait;

class HomeController
{
    use PrototypeTrait;

    public function index(DirectoriesInterface $dirs)
    {
        $this-&gt;files-&gt;ensureDirectory(
            $dirs-&gt;get('customDir'),
            FilesInterface::READONLY // 或者 FilesInterface::RUNTIME 使目录和文件可编辑
        );
    }
}
</code></pre>
<p>检查目录是否存在：</p>
<pre><code class=language-php>dump($files-&gt;isDirectory(__DIR__));
</code></pre>
<h3 id=删除目录>删除目录</h3>
<p>删除指定目录及该目录下的内容：</p>
<pre><code class=language-php>$files-&gt;deleteDirectory('custom');
</code></pre>
<p>只删除指定目录下的内容，不删除目录本身：</p>
<pre><code class=language-php>$files-&gt;deleteDirectory('custom', true);
</code></pre>
<h2 id=文件信息>文件信息</h2>
<p>检查文件是否存在：</p>
<pre><code class=language-php>dump($files-&gt;exists(__FILE__)); // bool
</code></pre>
<p>获取文件的创建或更新时间：</p>
<pre><code class=language-php>dump($files-&gt;time(__FILE__)); // unix timestamp
</code></pre>
<p>获取文件的 MD5 值；</p>
<pre><code class=language-php>dump($files-&gt;md5('filename'));
</code></pre>
<p>获取文件名中的扩展名：</p>
<pre><code class=language-php>dump($files-&gt;extension(__FILE__)); // without leading &quot;.&quot;
</code></pre>
<p>检查指定的路径是否文件：</p>
<pre><code class=language-php>dump($files-&gt;isFile(__DIR__));
</code></pre>
<p>获取文件的大小：</p>
<pre><code class=language-php>dump($files-&gt;size(__DIR__));
</code></pre>
<h3 id=权限>权限</h3>
<p>获取指定文件/目录的权限：</p>
<pre><code class=language-php>dump($files-&gt;getPermissions(__FILE__)); // int
</code></pre>
<p>设置文件权限：</p>
<pre><code class=language-php>$files-&gt;setPermissions(__FILE__, 0777)
</code></pre>
<p>常量与文件权限掩码关系：</p>
<table>
<thead>
<tr>
<th>常量</th>
<th>掩码</th>
</tr>
</thead>
<tbody>
<tr>
<td>FilesInterface::READONLY</td>
<td>644</td>
</tr>
<tr>
<td>FilesInterface::RUNTIME</td>
<td>666</td>
</tr>
</tbody>
</table>
<h2 id=移动和复制>移动和复制</h2>
<p>复制文件：</p>
<pre><code class=language-php>$files-&gt;copy('old-path', 'new-path');
</code></pre>
<p>移动文件：</p>
<pre><code class=language-php>$files-&gt;move('old-path', 'new-path');
</code></pre>
<h3 id=临时文件>临时文件：</h3>
<p><em>生成</em>临时文件名：</p>
<pre><code class=language-php>dump($files-&gt;tempFilename());
</code></pre>
<p>生成特定后缀的临时文件名：</p>
<pre><code class=language-php>dump($files-&gt;tempFilename('php'));
</code></pre>
<p>在指定的路径下生成临时文件名：</p>
<pre><code class=language-php>dump($files-&gt;tempFilename('php', __DIR__));
</code></pre>
<h2 id=读写操作>读写操作</h2>
<p>文件组件还提供了多个方法，用来以原子方式（无需获取文件资源）处理文件内容：</p>
<h3 id=创建写入文件>创建/写入文件</h3>
<p>把内容写入到指定文件（排它锁）：</p>
<pre><code class=language-php>$files-&gt;write('filename', 'data');
</code></pre>
<p>创建/写入文件并制定文件的访问权限：</p>
<pre><code class=language-php>$files-&gt;write('filename', 'data', 0777);
</code></pre>
<p>检查并自动创建路径中不存在的目录：</p>
<pre><code class=language-php>$files-&gt;write('filename', 'data', 0777, true);
</code></pre>
<blockquote>
<p>请注意，如果文件不可写，需要处理 <code>Spiral\Files\Exception\WriteErrorException</code> 异常。</p>
</blockquote>
<h3 id=增加内容>增加内容</h3>
<p>把内容追加到文件：</p>
<pre><code class=language-php>$files-&gt;append('filename', 'data');
</code></pre>
<p>增加内容到文件并指定文件权限：</p>
<pre><code class=language-php>$files-&gt;append('filename', 'data', 0777);
</code></pre>
<p>追加/创建文件，并自动创建路径中不存在的目录：</p>
<pre><code class=language-php>$files-&gt;append('filename', 'data', 0777, true);
</code></pre>
<h3 id=touch>Touch</h3>
<p>Linux 下的 touch 命令用于修改文件或目录的时间属性，如果文件不存在则会自动创建一个新的。Spiral 中文件对象的 <code>touch</code> 方法功能与之类似：</p>
<pre><code class=language-php>$files-&gt;touch('filename');
</code></pre>
<p>Touch 文件并确保它具有指定的权限：</p>
<pre><code class=language-php>$files-&gt;touch('filename', 0777);
</code></pre>
<h3 id=读取文件>读取文件</h3>
<p>读取指定文件的内容：</p>
<pre><code class=language-php>dump($files-&gt;read('filename'));
</code></pre>
<blockquote>
<p>注意：如果文件不存在，需要处理 <code>Spiral\Files\Exception\FileNotFoundException</code> 异常。</p>
</blockquote>
</div>
<div class=article-widget>
<div class=post-nav>
<div class=post-nav-item>
<div class=meta-nav>上一页</div>
<a href=/docs/component/reactor/ rel=next>代码生成</a>
</div>
<div class=post-nav-item>
<div class=meta-nav>下一页</div>
<a href=/docs/cookbook/custom-dispatcher/ rel=prev>速查手册 - 自定义调度器</a>
</div>
</div>
</div>
</div>
<div class=body-footer>
<p>最近更新于 2020-04-13</p>
<p class=edit-page>
<a href=https://github.com/krwu/spiraldocs/edit/feat/chinese/zh_CN/component/files.md>
<i class="fas fa-pen pr-2"></i>编辑本页
</a>
</p>
</div>
</article>
<footer class=site-footer>
<p class=powered-by><span class=copyright>© 2019 - 2021 <a href=https://studyspiral.cn/>StudySpiral</a> All rights reserved.</span>
</p>
<p class=powered-by>
<a href=http://www.beian.miit.gov.cn/ target=_blank rel="noopener noreferer">粤ICP备14011364号</a>
<a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030402001866" target=_blank rel="noopener noreferer"><img style=display:inline-block src=/img/gaba.png>粤公网安备 44030402001866号</a>
</p>
<p id=webify class=powered-by style=display:flex><span style="margin:0 .2rem 0 0;display:block;height:20px;line-height:20px">Powered by</span> <a href=https://webify.cloudbase.net/ target=_blank rel=noopener>CloudBase Webify</a></p>
<script async defer>window.addEventListener('DOMContentLoaded',()=>{const{host:a}=window.location;(a.toLocaleLowerCase()==='docs.studyspiral.cn'||a.indexOf(".app.tcloudbase.com"))&&(document.getElementById('webify').style.display='flex')})</script>
</footer>
</main>
</div>
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/go.min.js></script>
<script>const code_highlighting=!0</script>
<script>const isSiteThemeDark=!1</script>
<script>const search_config={indexURI:"/index.json",minLength:1,threshold:.3},i18n={no_results:"没有找到结果",placeholder:"搜索...",results:"搜索结果"},content_type={post:"文章",project:"项目",publication:"出版物",talk:"演讲"}</script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.1/anchor.min.js integrity="sha256-pB/deHc9CGfFpJRjC43imB29Rse8tak+5eXqntO94ck=" crossorigin=anonymous></script>
<script>anchors.add()</script>
<script id=search-hit-fuse-template type=text/x-template>
      <div class="search-hit" id="summary-{{key}}">
      <div class="search-hit-content">
        <div class="search-hit-name">
          <a href="{{relpermalink}}">{{title}}</a>
          <div class="article-metadata search-hit-type">{{type}}</div>
          <p class="search-hit-description">{{snippet}}</p>
        </div>
      </div>
      </div>
    </script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin=anonymous></script>
<script src=/js/academic.min.6f1005d1a84220e2f466ff3d8e712f31.js></script>
<div id=modal class="modal fade" role=dialog>
<div class=modal-dialog>
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title>引用</h5>
<button type=button class=close data-dismiss=modal aria-label=Close>
<span aria-hidden=true>&#215;</span>
</button>
</div>
<div class=modal-body>
<pre><code class="tex hljs"></code></pre>
</div>
<div class=modal-footer>
<a class="btn btn-outline-primary my-1 js-copy-cite" href=# target=_blank>
<i class="fas fa-copy"></i> 复制
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href=# target=_blank>
<i class="fas fa-download"></i> 下载
</a>
<div id=modal-error></div>
</div>
</div>
</div>
</div>
</body>
</html>